#include "video_stream_capture.h"
#include <QDateTime>
#include <QDir>


video_stream_capture::video_stream_capture(QObject *parent) :
    QThread(parent)
{
    vd=new video_device(FILE_VIDEO);
    refresh_timer=new QTimer();
    connect(refresh_timer,SIGNAL(timeout()),this,SLOT(save_video_file()));
   // refresh_timer->start(10000);
    second_timer=new QTimer();
    connect(second_timer,SIGNAL(timeout()),this,SLOT(second_timeout()));
    second_timer->start(1000);

    QDir dir("/run/video");
    if(!dir.exists()) dir.mkpath("/run/video");
    QDir::setCurrent("/run/video");
    QString filename=QDateTime::currentDateTime().toString("hh") + ".mp4";
//    videoFile = new QFile( filename +".mp4" );
//     if ( !videoFile->open( QIODevice::WriteOnly ) )
//     return;
     encoder = new XvidCodec( VIDEO_WIDTH, VIDEO_HEIGHT);
     mp4Buffer = new unsigned char[VIDEO_WIDTH*VIDEO_HEIGHT*8];
     rtpsender.init_rtplib( LOIPADDR,8008,8000);
    QByteArray ba = filename.toLatin1();
    mp4interface.open_mp4_file(ba.data());

}

 video_stream_capture::~video_stream_capture()
{
    delete vd;
    delete encoder;
    delete mp4Buffer;
    delete refresh_timer;
    delete second_timer;

}

void video_stream_capture::run()
{


    while (1)
    {
    vd->video_grab();
    process_frame=watermark(vd->frame);
    recordFrame();
    emit frame_changed();
    }

}
void video_stream_capture::save_video_file()
{
    videoFile->flush();
}
void video_stream_capture::recordFrame()
{

   qint64 m4vsize = encoder->encode( process_frame.bits(), mp4Buffer );
   sendbytes= QByteArray::fromRawData((const char*)mp4Buffer,m4vsize);
   rtpsender.send_rtp_data(sendbytes );
  // videoFile->write( sendbytes);
    mp4interface.write_one_frame(mp4Buffer,m4vsize);
   mp4interface.encoded_frame_queue.enqueue(sendbytes);
}

QImage video_stream_capture::watermark(QImage& image)
{
    QPainter image_painter(&image);
    image_painter.setPen(QColor(255,0,0));
    image_painter.drawText(500,450,datetimestring);
    image_painter.end();
    return image;

}


void video_stream_capture::second_timeout()
{
    datetimestring=QDateTime::currentDateTime().toString("hh:mm:ss yyyy.MM.dd");

}

